package com.weiwei.diancan.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.R;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.ChartBean;
import com.weiwei.diancan.bean.FindOrderBean;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;


import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;

public class PessmiseActivity extends BaseActivity {

    private TextView tv_date_start;
    private TextView tv_date_end;
    private TextView tv_chankan;
    private TextView tv_panghang;
    private TextView tv_finish_order;
    private TextView tv_people;
    private TextView tv_qian;
    private TextView tv_search;
    private TextView tv_totel;
    private TextView tv_everyone;

    private List<FindOrderBean.OrderListBean> order_list;
    private List<FindOrderBean.DishListBean> dish_list;
    private LineChart mChart;
    private TextView tv_ri,tv_yue,tv_nian;
    private int type = 1;  //1.日表  2.月表  3.年表
    private ChartBean chartBean;
    private LimitLine yLimitLine;

    @Override
    public void getData() {
        getfind_chart();
    }

    @Override
    public void setListeners() {
        tv_date_start.setOnClickListener(v -> initDate(tv_date_start));
        tv_date_end.setOnClickListener(v -> initDate(tv_date_end));
        tv_chankan.setOnClickListener(v -> {
            Intent intent = new Intent(PessmiseActivity.this, SearchOrderActivity.class);
            intent.putExtra("start", tv_date_start.getText().toString());
            intent.putExtra("end", tv_date_end.getText().toString());
            intent.putExtra("value", (Serializable) order_list);
            startActivity(intent);
        });
        tv_panghang.setOnClickListener(v -> {
            Intent intent = new Intent(PessmiseActivity.this, PaihangOrderActivity.class);
            intent.putExtra("start", tv_date_start.getText().toString());
            intent.putExtra("end", tv_date_end.getText().toString());
            intent.putExtra("value", (Serializable) dish_list);
            startActivity(intent);
        });
        tv_search.setOnClickListener(v -> getfind_order());

        tv_ri.setOnClickListener(v->{
            type = 1;
            setState();
            setChart();
        });
        tv_yue.setOnClickListener(v->{
            type = 2;
            setState();
            setChart();
        });
        tv_nian.setOnClickListener(v->{
            type = 3;
            setState();
            setChart();
        });
    }

    private void setState(){
        switch (type){
            case 1:
                tv_ri.setTextColor(Color.parseColor("#B41B1B"));
                tv_yue.setTextColor(Color.parseColor("#000000"));
                tv_nian.setTextColor(Color.parseColor("#000000"));
                break;
            case 2:
                tv_ri.setTextColor(Color.parseColor("#000000"));
                tv_yue.setTextColor(Color.parseColor("#B41B1B"));
                tv_nian.setTextColor(Color.parseColor("#000000"));
                break;
            case 3:
                tv_ri.setTextColor(Color.parseColor("#000000"));
                tv_yue.setTextColor(Color.parseColor("#000000"));
                tv_nian.setTextColor(Color.parseColor("#B41B1B"));
                break;
        }
    }

    @Override
    public void initView() {
        tv_date_start = (TextView) findViewById(R.id.tv_date_start);
        tv_date_end = (TextView) findViewById(R.id.tv_date_end);
        tv_chankan = (TextView) findViewById(R.id.tv_chankan);
        tv_panghang = (TextView) findViewById(R.id.tv_panghang);

        tv_finish_order = (TextView) findViewById(R.id.tv_finish_order);
        tv_people = (TextView) findViewById(R.id.tv_people);
        tv_qian = (TextView) findViewById(R.id.tv_qian);
        tv_totel = (TextView) findViewById(R.id.tv_totel);
        tv_everyone = (TextView) findViewById(R.id.tv_everyone);

        tv_ri = (TextView)findViewById(R.id.tv_ri);
        tv_yue = (TextView)findViewById(R.id.tv_yue);
        tv_nian = (TextView)findViewById(R.id.tv_nian);


        tv_search = (TextView) findViewById(R.id.tv_search);

        mChart = (LineChart) findViewById(R.id.chart_day);


        //初始化日期，以当前日期为准拉取订单
        setDate();

    }

    @Override
    public void initTitle() {
        titler.setText("权限查看");
        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener(v -> finish());
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_pessmise);

    }

    private void setDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());

        tv_date_start.setText(format);
        tv_date_end.setText(format);
    }


    /**
     * 日期框
     *
     * @param textView
     */
    public void initDate(TextView textView) {
        Calendar c = Calendar.getInstance();
        String date = textView.getText().toString();

        int current_year = c.get(Calendar.YEAR);
        int current_month = c.get(Calendar.MONTH);
        int current_day = c.get(Calendar.DAY_OF_MONTH);

        if (!TextUtils.isEmpty(date)) {
            String[] split = date.split("-");
            current_year = Integer.parseInt(split[0]);
            current_month = Integer.parseInt(split[1]) - 1;
            current_day = Integer.parseInt(split[2]);
        }
        new DatePickerDialog(this, (view, year, month, dayOfMonth) ->
                textView.setText(year + "-" + (month + 1) + "-" + dayOfMonth),
                current_year, current_month, current_day).show();
    }


    /**
     * 获取权限管理
     */
    private void getfind_order() {
        progressDialog.setMessage("数据获取中...");
        progressDialog.show();
        String start_date = tv_date_start.getText().toString().trim();
        String date_end = tv_date_end.getText().toString().trim();

        if (!checkDate(start_date.split("-"), date_end.split("-"), 0)) {
            ToastUtil.showToast(this, "结束日期必须大于开始日期！");
            progressDialog.cancel();
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token, CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token, CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.date_start, start_date);
        map.put(ConfigMethod.date_end, date_end);

        RetrofitFactory.getIntance().find_order(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<FindOrderBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        ToastUtil.showToast(PessmiseActivity.this, "网络连接异常");
                    }

                    @Override
                    public void onNext(FindOrderBean findOrderBean) {
                        progressDialog.cancel();
                        if (findOrderBean.getIs_success().equals("1")) {
                            setViewData(findOrderBean);
                        } else if (findOrderBean.getIs_success().equals("-1")) {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        } else if (findOrderBean.getIs_success().equals("-2")) {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        } else {
                            ToastUtil.showToast(PessmiseActivity.this, findOrderBean.getReason());
                        }
                    }
                });
    }

    /**
     * 获取图表数据
     */
    private void getfind_chart() {
        progressDialog.setMessage("数据获取中...");
        progressDialog.show();


        Map<String, String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token, CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token, CacheConfig.getInst().getWaterToken(this));


        RetrofitFactory.getIntance().find_chart(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ChartBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        ToastUtil.showToast(PessmiseActivity.this, "网络连接异常");
                    }

                    @Override
                    public void onNext(ChartBean chartBeans) {
                        progressDialog.cancel();
                        if (chartBeans.getIs_success().equals("1")) {
                            getfind_order();

                            chartBean = chartBeans;
                            type = 3;
                            setChart();

                        } else if (chartBeans.getIs_success().equals("-1")) {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        } else if (chartBeans.getIs_success().equals("-2")) {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        } else {
                            ToastUtil.showToast(PessmiseActivity.this, chartBeans.getReason());
                        }
                    }
                });
    }

    /**
     * 设置界面数据
     */
    private void setViewData(FindOrderBean findOrderBean) {
        List<FindOrderBean.OrderListBean> order_lists = findOrderBean.getOrder_list();
        List<FindOrderBean.DishListBean> dish_lists = findOrderBean.getDish_list();

        if (order_lists == null) {
            order_lists = new ArrayList<>();
        }

        if (dish_lists == null) {
            dish_lists = new ArrayList<>();
        }

        this.order_list = order_lists;
        this.dish_list = dish_lists;

        int people = 0;//上客人数
        int counts = 0;//销量
        double totle = 0;//营收总额

        for (FindOrderBean.OrderListBean orderListBean : order_list) {
            String order_person = orderListBean.getOrder_person();
            String order_price = orderListBean.getOrder_price();
            if(TextUtils.isEmpty(order_price)){
                order_price = "0";
            }
            people += Integer.parseInt(order_person);
            totle += Double.parseDouble(order_price);
        }

        for (FindOrderBean.DishListBean dishListBean : dish_list) {
            String counts1 = dishListBean.getCounts();
            counts += Integer.parseInt(counts1);
        }

        tv_finish_order.setText(order_list.size() + "/单");
        tv_people.setText(people + "/人");
        tv_qian.setText(counts + "");
        tv_totel.setText("¥" + totle);

        if (people == 0) {
            tv_everyone.setText("¥0");
        } else {
            double eo = totle / people;
            BigDecimal b = new BigDecimal(eo);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            tv_everyone.setText("¥" + f1);
        }
    }

    /**
     * 日期检查
     *
     * @return
     */
    private boolean checkDate(String start[], String end[], int i) {
        int i1 = Integer.parseInt(start[i]);
        int i2 = Integer.parseInt(end[i]);

        if (i2 < i1) return false;
        else if (i2 > i1) return true;
        else {
            if (i + 1 == start.length) return true;
            else return checkDate(start, end, ++i);
        }
    }

    /**
     * 设置折线图
     */
    private void setChart() {


        // no description text
        switch (type){
            case 1:
                mChart.setDescription("日统计表");
                break;
            case 2:
                mChart.setDescription("月统计表");
                break;
            case 3:
                mChart.setDescription("年统计表");
                break;
        }

        // enable touch gestures
        mChart.setTouchEnabled(true);

        mChart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);

        // set an alternative background color
        mChart.setBackgroundColor(Color.WHITE);

        // add data
        switch (type){
            case 1:
                setData(chartBean.getDay_charts().size());
                break;
            case 2:
                setData(chartBean.getMonth_charts().size());
                break;
            case 3:
                setData(chartBean.getYear_charts().size());
                break;
        }

        mChart.animateX(1000);

        Legend l = mChart.getLegend();
        l.setEnabled(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setTextSize(5f);
        xAxis.setTextColor(Color.BLACK);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        //设置X轴的文字在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTextColor(Color.parseColor("#3F51B5"));
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setTextColor(Color.parseColor("#B41B1B"));
        rightAxis.setAxisMinValue(-1000);
        rightAxis.setDrawGridLines(false);
        rightAxis.setDrawZeroLine(false);
        rightAxis.setGranularityEnabled(false);

        // 设置x轴的LimitLine
//        float value = 0;
//        float totel = 0;
//        int person = 0;
//        switch (type){
//            case 1:
//                List<ChartBean.DayChartsBean> day_charts = chartBean.getDay_charts();
//                for(int i = 0;i<day_charts.size();i++){
//                    totel += Float.parseFloat(day_charts.get(i).getOrder_price());
//                    person +=Integer.parseInt(day_charts.get(i).getOrder_person());
//                }
//                value = totel/person;
//                break;
//            case 2:
//                List<ChartBean.MonthChartsBean> month_charts = chartBean.getMonth_charts();
//                for(int i = 0;i<month_charts.size();i++){
//                    totel += Float.parseFloat(month_charts.get(i).getOrder_price());
//                    person +=Integer.parseInt(month_charts.get(i).getOrder_person());
//                }
//                value = totel/person;
//                break;
//            case 3:
//                List<ChartBean.YearChartsBean> year_charts = chartBean.getYear_charts();
//                for(int i = 0;i<year_charts.size();i++){
//                    totel += Float.parseFloat(year_charts.get(i).getOrder_price());
//                    person +=Integer.parseInt(year_charts.get(i).getOrder_person());
//                }
//                value = totel/person;
//                break;
//        }
//        BigDecimal b = new BigDecimal(value);
//        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//
//            leftAxis.removeAllLimitLines();
//        yLimitLine = new LimitLine(Float.parseFloat(f1+""),"人均：¥"+f1);
//        yLimitLine.setLineColor(getResources().getColor(R.color.cffa800));
//        yLimitLine.setTextColor(Color.BLACK);
//        yLimitLine.setLineWidth(2);
//        yLimitLine.setTextSize(11f);
//        // 获得左侧侧坐标轴
//        leftAxis.addLimitLine(yLimitLine);

    }

    private void setData(int count) {

        List<ChartBean.DayChartsBean> day_charts = chartBean.getDay_charts();
        List<ChartBean.MonthChartsBean> month_charts = chartBean.getMonth_charts();
        List<ChartBean.YearChartsBean> year_charts = chartBean.getYear_charts();

//        // 设置x轴的LimitLine
//        LimitLine yLimitLine = new LimitLine(50f,"人均：¥50");
//        yLimitLine.setLineColor(Color.parseColor("#cffa800"));
//        yLimitLine.setTextColor(Color.BLACK);
//        yLimitLine.setTextSize(11f);
//        // 获得左侧侧坐标轴
//        YAxis leftAxis = mChart.getAxisLeft();
//        leftAxis.addLimitLine(yLimitLine);

        //营收
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            float val = 0;
            switch (type){
                case 1:
                    val = Float.parseFloat(day_charts.get(i).getOrder_price());
                    break;
                case 2:
                    val = Float.parseFloat(month_charts.get(i).getOrder_price());
                    break;
                case 3:
                    val = Float.parseFloat(year_charts.get(i).getOrder_price());
                    break;
            }
            yVals1.add(new Entry(val, i));
        }

        //人数
        ArrayList<Entry> yVals2 = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            int val = 0;
            switch (type){
                case 1:
                    val =Integer.parseInt(day_charts.get(i).getOrder_person());
                    break;
                case 2:
                    val =Integer.parseInt(month_charts.get(i).getOrder_person());
                    break;
                case 3:
                    val =Integer.parseInt(year_charts.get(i).getOrder_person());
                    break;
            }
            yVals2.add(new Entry(val, i));
        }

        //人均
        ArrayList<Entry> yVals3 = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            float val = 0;
            switch (type){
                case 1:
                    float b = Float.parseFloat(day_charts.get(i).getOrder_price());
                    int a = Integer.parseInt(day_charts.get(i).getOrder_person());
                    if(a == 0){
                        val = 0.0f;
                    }else {
                        BigDecimal s = new BigDecimal(b / a);
                        double f = s.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        val = Float.parseFloat(f + "");
                    }
                    break;
                case 2:
                    float b1 = Float.parseFloat(month_charts.get(i).getOrder_price());
                    int a1 = Integer.parseInt(month_charts.get(i).getOrder_person());
                    if(a1 == 0){
                        val = 0.0f;
                    }else {
                        BigDecimal s1 = new BigDecimal(b1 / a1);
                        double f1 = s1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        val = Float.parseFloat(f1 + "");
                    }
                    break;
                case 3:
                    float b2 = Float.parseFloat(year_charts.get(i).getOrder_price());
                    int a2 = Integer.parseInt(year_charts.get(i).getOrder_person());
                    if(a2 == 0){
                        val = 0.0f;
                    }else {
                        BigDecimal s2 = new BigDecimal(b2 / a2);
                        double f2 = s2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        val = Float.parseFloat(f2 + "");
                    }
                    break;
            }
            yVals3.add(new Entry(val, i));
        }

        Log.e("tag","u===="+yVals3.toString());

        LineDataSet set1, set2 ,set3;
        set1 = new LineDataSet(yVals1, "营收");

        set1.setAxisDependency(YAxis.AxisDependency.RIGHT);
        set1.setColor(Color.parseColor("#B41B1B"));
        set1.setCircleColor(Color.parseColor("#B41B1B"));
        set1.setLineWidth(2f);
        set1.setCircleRadius(3f);
        set1.setFillAlpha(65);
        set1.setFillColor(Color.parseColor("#B41B1B"));
        set1.setHighLightColor(Color.parseColor("#B41B1B"));
        set1.setDrawCircleHole(false);

        set2 = new LineDataSet(yVals2, "人数");
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);
        set2.setColor(Color.parseColor("#3F51B5"));
        set2.setCircleColor(Color.parseColor("#3F51B5"));
        set2.setLineWidth(2f);
        set2.setCircleRadius(3f);
        set2.setFillAlpha(65);
        set2.setFillColor(Color.parseColor("#3F51B5"));
        set2.setDrawCircleHole(false);
        set2.setHighLightColor(Color.parseColor("#3F51B5"));

        set3 = new LineDataSet(yVals3, "人均");
        set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
        set3.setColor(Color.parseColor("#ffa800"));
        set3.setCircleColor(Color.parseColor("#ffa800"));
        set3.setLineWidth(2f);
        set3.setCircleRadius(3f);
        set3.setFillAlpha(65);
        set3.setFillColor(Color.parseColor("#ffa800"));
        set3.setDrawCircleHole(false);
        set3.setHighLightColor(Color.parseColor("#ffa800"));

        ArrayList<String> xValues = new ArrayList<>();
        for (int i = 0; i < day_charts.size(); i++) {
            switch (type){
                case 1:
                    xValues.add(day_charts.get(i).getDay());
                    break;
                case 2:
                    xValues.add(month_charts.get(i).getMonth());
                    break;
                case 3:
                    xValues.add(year_charts.get(i).getYear());
                    break;
            }

        }

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();

        dataSets.add(set2);
        dataSets.add(set3);
        dataSets.add(set1);


        LineData data = new LineData(xValues, dataSets);
        data.setValueTextColor(Color.BLACK);
        data.setValueTextSize(9f);

        mChart.setData(data);
    }

}
